<template>
  <el-form-item class="common-form-width" label="商品规格" prop="products" :rules="rules">
    <div class="item-inner-content">
      <div class="inner-main">
        <el-select v-model="modelValue" @change="handleChange" placeholder="请选择规格">
          <el-option v-for="(item) in options" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </div>
      <div class="inner-append">
        <slot name="append"></slot>
      </div>
    </div>
  </el-form-item>
</template>

<script lang="ts" setup>
import {IGoodsPageRow, IStoreProductRow} from "@/api/modules/pointsMall";
import {WritableComputedRef} from "vue";
import {IAddGiftPackData} from "@/api/modules/vipCenter";

const props = defineProps<{
  modelValue: number | null,
  options: IStoreProductRow[],
  giftPackForm?: IAddGiftPackData,
  giftPackPageRow?: IGoodsPageRow
}>()

const emits = defineEmits<{
  (e: 'change', value: number):void,
  (e: 'update:model-value', value: number | null): void
}>()

const modelValue:WritableComputedRef<number | null> = computed({
  set(newValue) {
    emits("update:model-value", newValue)
  },
  get() {
    return props.modelValue
  }
})

const handleChange = (id: number) => {
  emits('change', id)
}

const rules = [{
  required: true,
  blur: 'change',
  validator (rules:any,value:any,callback:any) {
    if (props.modelValue === null) {
      callback('请选择商品规格')
      return
    }

    const currentOption = props.options.find(item => item.id === props.modelValue)

    // 规则A 和 规则B的逻辑是一致的，仅数据来源上的区别
    // 规则A
    if (props.giftPackForm) {
      if (props.giftPackForm.packNum !== -1 && currentOption!.beforeStock < props.giftPackForm.addOrDeductionStockCount) {
        callback(`该规格库存 < 礼品包库存（${props.giftPackForm.addOrDeductionStockCount}）,请重新选择`)
        return
      }
    }

    // 规则B
    if (props.giftPackPageRow) {
      if (props.giftPackPageRow.packNum !== -1 && currentOption!.beforeStock < props.giftPackPageRow.stock!) {
        callback(`该规格库存 < 礼品包库存（${props.giftPackPageRow.stock}）,请重新选择`)
        return
      }
    }

    callback()
  }
}]
</script>

<style scoped lang="scss">
@use "@/components/goodsCenter/styles/common.scss";

.item-inner-content {
  display: flex;
  align-items: center;

  .inner-append {
    margin-left: 10px;
  }
}
</style>
